//
//  StringExtensions.swift
//  FoundationCustom
//
//  Created by ZhouJiatao on 2018/12/27.
//  Copyright © 2018 Unknow. All rights reserved.
//

import Foundation

public extension String {
    var isNotEmpty: Bool {
        return !self.isEmpty
    }
    
    /// 转为double类型，默认值0.0
    func toDoubleSafe() -> Double {
        return Double(self) ?? 0.0
    }
    
    func toIntSafe() -> Int {
        return Int(self) ?? 0
    }
    
    
    /// 手机号码隐藏中间4位
    func phonePrivacy() -> String {
        guard self.count > 7 else {
            return self
        }
        let start = self.index(self.startIndex, offsetBy: 3)
        let end = self.index(self.startIndex, offsetBy: 7)
        let range = Range(uncheckedBounds: (lower: start, upper: end))
        return self.replacingCharacters(in: range, with: "****")
    }
    
    /// 汉字转拼音
    func pinYin(separator: String = "") -> String {
        
        let mutableString = NSMutableString(string: self)
        //把汉字转为拼音
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        //去掉拼音的音标
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)

        let string = String(mutableString)
        
        //默认已经是空格分隔符
        if(separator == " ") {
            return string
            
        }
        
        return string.replacingOccurrences(of: " ", with: separator)
    }
    
}
